package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.dateVo.OrderNoGenerator;
import com.bwie.mapper.CouponListMapper;
import com.bwie.pojo.CouponList;
import com.bwie.pojo.TbOrder;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author lenovo
 * @description 针对表【tb_order(订单表)】的数据库操作Service实现
 * @createDate 2025-07-11 16:04:07
 */
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
        implements TbOrderService {

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    OrderNoGenerator orderNoGenerator;

    @Autowired
    HttpServletRequest request;

    @Autowired
    CouponListMapper couponListMapper;

    @Override
    public R addOrder(TbOrder tbOrder) {

        String nextNo = orderNoGenerator.nextNo();

        String token = request.getHeader("token");

        Integer customerId = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("customerId", Integer.class);

        tbOrder.setCustomerId(customerId);

        tbOrder.setOrderNumber(nextNo);

        tbOrder.setStatus(0);

        tbOrder.setActualAmount(tbOrder.getPrice());

        //查询优惠金额
        CouponList couponList = couponListMapper.selectOne(
                new QueryWrapper<CouponList>().lambda().eq(CouponList::getId, tbOrder.getCouponId())
        );
        tbOrder.setDiscount(couponList.getCouponPrice());
        //实际金额
        tbOrder.getPrice().subtract(tbOrder.getDiscount());
        tbOrderMapper.insert(tbOrder);
        return R.OK();
    }

    @Override
    public R getOrderList() {

        List<TbOrder> tbOrders = tbOrderMapper.selectList(null);

        return R.OK(tbOrders);
    }

    @Override
    public void updateByPayStatus(String out_trade_no) {
        tbOrderMapper.updateByPayStatus(out_trade_no);
    }
}




